import React, { useState, useEffect } from 'react';
import { Card, Button, Space, message, Table, Tag, Typography, Row, Col, Input, Select } from '@/utils/antd-imports';
import { UserOutlined, ReloadOutlined } from '@/utils/icons';
import userApi from '../api/userApi';
import employeeApi from '../api/employeeApi';
import moment from 'moment';

const { Title, Text } = Typography;
const { Option } = Select;

// 用户类型映射
const userTypeMap = {
  'super_admin': '总管理员',
  'admin': '管理员',
  'sub_admin': '子管理员',
  'user': '普通用户'
};

const UserManagementTest = () => {
  const [users, setUsers] = useState([]);
  const [employees, setEmployees] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');

  // 加载用户列表
  const loadUsers = async () => {
    try {
      setLoading(true);
      console.log('开始加载用户列表...');
      const response = await userApi.getUserList();
      console.log('用户列表响应:', response);
      
      if (response.code === 200) {
        setUsers(response.data || []);
        message.success(`成功加载 ${response.data?.length || 0} 个用户`);
      } else {
        message.error(response.message || '加载用户列表失败');
      }
    } catch (error) {
      console.error('加载用户列表失败:', error);
      message.error('加载用户列表失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 测试创建用户
  const testCreateUser = async () => {
    try {
      const testUserData = {
        username: `test_user_${Date.now()}`,
        password: '123456',
        administrator: 0,
        employeeId: 1
      };
      
      console.log('测试创建用户:', testUserData);
      const response = await userApi.createUser(testUserData);
      console.log('创建用户响应:', response);
      
      if (response.code === 200) {
        message.success('测试用户创建成功');
        loadUsers(); // 重新加载用户列表
      } else {
        message.error(response.message || '创建用户失败');
      }
    } catch (error) {
      console.error('创建用户失败:', error);
      message.error('创建用户失败: ' + error.message);
    }
  };

  // 测试删除用户
  const testDeleteUser = async (username) => {
    try {
      console.log('测试删除用户:', username);
      const response = await userApi.deleteUser(username);
      console.log('删除用户响应:', response);
      
      if (response.code === 200) {
        message.success('用户删除成功');
        loadUsers(); // 重新加载用户列表
      } else {
        message.error(response.message || '删除用户失败');
      }
    } catch (error) {
      console.error('删除用户失败:', error);
      message.error('删除用户失败: ' + error.message);
    }
  };

  // 测试权限提升
  const testPromoteAdmin = async (username) => {
    try {
      console.log('测试提升用户权限:', username);
      const response = await userApi.promoteAdmin(username);
      console.log('权限提升响应:', response);
      
      if (response.code === 200) {
        message.success('权限提升成功');
        loadUsers(); // 重新加载用户列表
      } else {
        message.error(response.message || '权限提升失败');
      }
    } catch (error) {
      console.error('权限提升失败:', error);
      message.error('权限提升失败: ' + error.message);
    }
  };

  // 加载员工列表
  const loadEmployees = async () => {
    try {
      console.log('开始加载员工列表...');
      const response = await employeeApi.getEmployeesByStatus(1); // 1表示在职员工
      console.log('员工列表响应:', response);
      
      if (response.code === 200) {
        setEmployees(response.data || []);
        message.success(`成功加载 ${response.data?.length || 0} 个员工`);
      } else {
        message.error(response.message || '加载员工列表失败');
      }
    } catch (error) {
      console.error('加载员工列表失败:', error);
      message.error('加载员工列表失败: ' + error.message);
    }
  };

  // 组件挂载时加载数据
  useEffect(() => {
    loadUsers();
    loadEmployees();
  }, []);

  // 筛选数据
  const filteredUsers = users.filter(user => {
    if (!searchText) return true;
    return (user.username && user.username.includes(searchText)) ||
           (user.employeeName && user.employeeName.includes(searchText));
  });

  // 表格列定义
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      render: (text) => <Text strong>{text}</Text>
    },
    {
      title: '员工姓名',
      dataIndex: 'employeeName',
      key: 'employeeName'
    },
    {
      title: '员工编号',
      dataIndex: 'employeeCode',
      key: 'employeeCode'
    },
    {
      title: '用户类型',
      dataIndex: 'userType',
      key: 'userType',
      render: (userType) => {
        const colors = {
          'super_admin': 'red',
          'admin': 'orange',
          'sub_admin': 'purple',
          'user': 'green'
        };
        return <Tag color={colors[userType]}>{userTypeMap[userType] || userType}</Tag>;
      }
    },
    {
      title: '管理员标识',
      dataIndex: 'administrator',
      key: 'administrator',
      render: (administrator) => (
        <Tag color={administrator ? 'blue' : 'default'}>
          {administrator ? '是' : '否'}
        </Tag>
      )
    },
    {
      title: '员工ID',
      dataIndex: 'employeeId',
      key: 'employeeId'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time) => time ? moment(time).format('YYYY-MM-DD HH:mm:ss') : '-'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          {record.userType === 'user' && (
            <Button 
              size="small"
              onClick={() => testPromoteAdmin(record.username)}
            >
              提升管理员
            </Button>
          )}
          <Button 
            size="small"
            danger
            onClick={() => testDeleteUser(record.username)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title="用户管理功能测试"
        extra={
          <Space>
            <Button 
              icon={<ReloadOutlined />}
              onClick={loadUsers}
              loading={loading}
            >
              刷新用户
            </Button>
            <Button 
              icon={<ReloadOutlined />}
              onClick={loadEmployees}
            >
              刷新员工
            </Button>
            <Button 
              type="primary"
              onClick={testCreateUser}
            >
              测试创建用户
            </Button>
          </Space>
        }
      >
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={8}>
            <Input
              placeholder="搜索用户名或员工姓名"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              allowClear
            />
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={filteredUsers}
          rowKey="username"
          loading={loading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
          }}
          scroll={{ x: 800 }}
          bordered
          size="middle"
        />
      </Card>

      {/* 员工列表显示 */}
      <Card 
        title="员工列表（用于关联用户）" 
        style={{ marginTop: 16 }}
        extra={
          <Button 
            icon={<ReloadOutlined />}
            onClick={loadEmployees}
          >
            刷新员工列表
          </Button>
        }
      >
        <Table
          columns={[
            {
              title: '员工ID',
              dataIndex: 'id',
              key: 'id',
              width: 80
            },
            {
              title: '员工编号',
              dataIndex: 'employeeCode',
              key: 'employeeCode',
              width: 120
            },
            {
              title: '姓名',
              dataIndex: 'name',
              key: 'name',
              width: 120
            },
            {
              title: '部门',
              dataIndex: 'department',
              key: 'department',
              width: 120
            },
            {
              title: '职位',
              dataIndex: 'position',
              key: 'position',
              width: 120
            },
            {
              title: '状态',
              dataIndex: 'status',
              key: 'status',
              width: 80,
              render: (status) => (
                <Tag color={status === 1 ? 'green' : 'red'}>
                  {status === 1 ? '在职' : '离职'}
                </Tag>
              )
            }
          ]}
          dataSource={employees}
          rowKey="id"
          pagination={{
            pageSize: 5,
            showSizeChanger: false,
            showTotal: (total) => `共 ${total} 个员工`
          }}
          scroll={{ x: 600 }}
          bordered
          size="small"
        />
      </Card>
    </div>
  );
};

export default UserManagementTest;
